package de.app.fbc.user

import java.util.logging.Logger;

import com.google.appengine.api.datastore.*

import org.apache.commons.codec.digest.DigestUtils;

import de.app.fbc.util.Tracer
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.io.SyndFeedOutput;
import com.sun.syndication.io.XmlReader;

class UserController {

	def persistenceManager
	def tracerService
	
	private static String BUNDESLIGA_FEED_ADRESS = "http://www.bundesliga.de/rss/de/liga/rss_news.xml";
	
	// the delete, save and update actions only accept POST requests
    static allowedMethods = [delete:'POST', save:'POST', update:'POST']
    
    def index = 
     {
 			def liste
 			def feed = new XmlSlurper().parse(BUNDESLIGA_FEED_ADRESS) 
 			
 			try
 			{
				liste = feed.channel.item;
	 		}
 			catch(Exception e){
 			
 			}
 	        [feed: liste]
 			
     }
    def list = {
        params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)
		def query = persistenceManager.newQuery( User )
		def  userInstanceList = query.execute()

                def queryrolle = persistenceManager.newQuery( Rolle )
		def  rolleInstanceList = queryrolle.execute()

		def total = 0
		if(  userInstanceList &&  userInstanceList.size() > 0){
			total =  userInstanceList.size()
		}
		[  userInstanceList :  userInstanceList,  userInstanceTotal: total, rolleList :  rolleInstanceList]
    }

    def show = {
	    def userInstance = persistenceManager.getObjectById( User.class, Long.parseLong( params.id )  )
        if(!userInstance) {
            flash.message = "User not found with id ${params.id}"
            redirect(action:list)
        }
        else { return [ userInstance : userInstance ] }
    }

    def delete = {
	    def userInstance = persistenceManager.getObjectById( User.class, Long.parseLong( params.id )  )
        if(userInstance) {
            try {
                persistenceManager.deletePersistent(userInstance)
                flash.message = "User ${params.id} deleted"
                redirect(action:list)
            }
            catch(Exception e) {
                flash.message = "User ${params.id} could not be deleted"
                redirect(action:show,id:params.id)
            }
        }
        else {
            flash.message = "User not found with id ${params.id}"
            redirect(action:list)
        }
    }

    def edit = {
	    def userInstance = persistenceManager.getObjectById( User.class, Long.parseLong( params.id )  )
		if(!userInstance) {
            flash.message = "User not found with id ${params.id}"
            redirect(action:list)
        }
        else {
			userInstance = persistenceManager.detachCopy( userInstance )    
        	return [ userInstance : userInstance ]
        }
    }

    def update = {
	def userInstance = persistenceManager.getObjectById( User.class, Long.parseLong( params.id )  )
    
    	if(userInstance) {
            userInstance.properties = params
            if(!userInstance.hasErrors()){
	
				try{
					persistenceManager.makePersistent(userInstance)
				} catch( Exception e ){
				   	render(view:'edit',model:[userInstance:userInstance])
				}finally{
					flash.message = "User ${params.id} updated"
	                redirect(action:show,id:userInstance.id)
				}        
 			}
            else {
                render(view:'edit',model:[userInstance:userInstance])
            }
        }
        else
        {
            flash.message = "User not found with id ${params.id}"
            redirect(action:list)
        }
    }

    def register = {
        def userInstance = new User()
        userInstance.properties = params
        return ['userInstance':userInstance]
    }
    def save = {
        def userInstance = new User(params)
        boolean fehler = false;
        String fehlermeldung = "Es fehlen noch Angaben";
        if(!params.loginName || params.loginName.equals(''))
        {
            fehler = true
        }
        if(!params.nachname || params.nachname.equals(''))
        {
            fehler = true
        }
        if(!params.email || params.nachname.equals(''))
        {
            fehler = true
        }
        if(!params.passwort1 || params.passwort1.equals('') || !params.passwort2 || params.passwort2.equals(''))
        {
            fehler = true
        }
        else if(!params.passwort1.equals(params.passwort2))
        {
            fehlermeldung = '\n Die Passwörter stimmen nicht überein.'
            fehler = true
        }
        else
        {
            String cryptopw = DigestUtils.md5Hex(params.passwort1)
            userInstance.passwort = cryptopw
        }
        if(fehler)
        {
            flash.error = fehlermeldung
            render(view:'register',model:[userInstance:userInstance])
        }
        else
        {
            def query = persistenceManager.newQuery(User.class);
            query.setFilter("loginName == loginNameParam");
            query.declareParameters("String loginNameParam");
            def user
            try
            {
                user = query.execute(params.loginName);
            }
            catch(Exception e){System.out.println(e)}
            finally
            {
                query.closeAll();
            }
            if(user)
            {
                flash.message = 'Loginname bereits vergeben'
                render(view:'register',model:[userInstance:userInstance])
            }
            else
            {
                try
                {
                    persistenceManager.makePersistent(userInstance)
                    flash.message = 'Zugang wurde erstellt. Du kannst dich jetzt einloggen'
                    redirect(uri:'/index.gsp')
                }
                catch(Exception e)
                {
                   //flash.message = e.toString();
                    render(view:'register',model:[userInstance:userInstance])
                }
            }
        }
    }
    def logout = {
    	def t = tracerService.generate(session.user, "Abgemeldet")
        persistenceManager.makePersistent(t)
        
        session.user = null;
        session.invalidate();
        flash.message = 'Erfolgreich abgemeldet. Bis zum nächsten Mal'
        redirect(uri:'/index.gsp')
    }
    def login =
    {
        def passwort = params.passwort
        def username = params.benutzername
        
        if(!params.passwort)
            redirect(uri:'/index.gsp')
        else
        {
            if(!params.benutzername)
                redirect(uri:'/index.gsp')
            else
            {


                def query = persistenceManager.newQuery(User.class);
                query.setFilter("loginName == loginNameParam && passwort == passwortParam");
                query.declareParameters("String loginNameParam, String passwortParam");
                def user
                try
                {
                    String cryptopw = DigestUtils.md5Hex(passwort)
                    user = query.execute(username, cryptopw).getAt(0);
                }
                catch(Exception e){}
                finally
                {
                    query.closeAll();
                }

                if(!user)
                {
                    flash.message = 'Benutzer nicht gefunden. Bitte registrieren'
                    redirect(uri:'/index.gsp')
                }
                else
                {
                    session.user = user.loginName
                    session.userID = user.key.id
                    
                    def t = tracerService.generate(user.loginName, "Angemeldet")
                    persistenceManager.makePersistent(t)
                    
                    redirect(action:'index')
                }
            }
        }
    }
   
}
